Micron Document




Java syntax
part 13/46 · 86.7 KB total
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
Possible values are listed using case labels. These labels in Java may contain only constants (including enum constants and string constants). Execution will start after the label corresponding to the expression inside the brackets. An optional default label may be present to declare that the code following it will be executed if none of the case labels correspond to the expression.

Code for each label ends with the break keyword. It is possible to omit it causing the execution to proceed to the next label, however, a warning will usually be reported during compilation.

switch (ch) {
case 'A':
doSomething(); // Triggered if ch == 'A'
break;
case 'B':
case 'C':
doSomethingElse(); // Triggered if ch == 'B' or ch == 'C'
break;
default:
doSomethingDifferent(); // Triggered in any other case
break;
}

switch expressions

Since Java 14 it has become possible to use switch expressions, which use the new arrow syntax:

var result = switch (ch) {
case 'A' -> Result.GREAT;
case 'B', 'C' -> Result.FINE;
default -> throw new ThisIsNoGoodException();
};

Alternatively, there is a possibility to express the same with the yield statement, although it is recommended to prefer the arrow syntax because it avoids the problem of accidental fall throughs.

var result = switch (ch) {
case 'A':
yield Result.GREAT;
case 'B':
case 'C':
yield Result.FINE;
default:
throw new ThisIsNoGoodException();
};

Iteration statements

──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────